package com.example.graduationdesign.controller;

import com.example.graduationdesign.mapper.CommonMapper;
import com.example.graduationdesign.mapper.ConsumerMapper;
import com.example.graduationdesign.pojo.dao.ArticleDao;
import com.example.graduationdesign.pojo.dao.UserDao;
import com.example.graduationdesign.pojo.dto.*;
import com.example.graduationdesign.pojo.vo.*;
import com.example.graduationdesign.service.CommonService;
import com.example.graduationdesign.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/user")
public class CommonController {

    @Autowired
    private CommonService commonService;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private ConsumerMapper consumerMapper;
    /**
     * 发送邮件获取验证码
     *
     * @param forgetPwdDto
     * @return
     */
    @PostMapping("/email")
    public Result<String> sendEmail(@RequestBody ForgetPwdDto forgetPwdDto) {
        System.out.println(forgetPwdDto);
        log.info("接收信息：{}", forgetPwdDto);
        if (!Optional.ofNullable(forgetPwdDto.getEmail()).isPresent()) {
            return Result.failure(ResultCode.PARAM_IS_NULL);

        }
        return Result.success(commonService.sendEmail(forgetPwdDto.getEmail()));
    }


    /**
     * 用于实现用户在注册时的邮箱验证
     * @param registerDto
     * @return
     */
    @PostMapping("/email/register")
    public Result<String> sendRegisterEmail(@RequestBody RegisterDto registerDto) {
        System.out.println(registerDto);
        log.info("接收信息：{}", registerDto);
        if (!Optional.ofNullable(registerDto.getEmail()).isPresent()) {
            return Result.failure(ResultCode.PARAM_IS_NULL);

        }
        return Result.success(commonService.sendRegisterEmail(registerDto.getEmail()));
    }


    /**
     * 注册用户获取验证码
     * @param modifyEmailDto
     * @return
     */
    @PostMapping("/send_email_code")
    public Result<String> sendModifyEmail(@RequestBody ModifyEmailDto modifyEmailDto) {
        System.out.println(modifyEmailDto);
        log.info("接收信息：{}", modifyEmailDto);
        if (!Optional.ofNullable(modifyEmailDto.getEmail()).isPresent()) {
            return Result.failure(ResultCode.PARAM_IS_NULL);

        }
        return Result.success(commonService.sendModifyEmail(modifyEmailDto.getEmail(),modifyEmailDto.getNewEmail()));
    }


    /**
     * 忘记密码
     *
     * @param forgetPwdDto
     * @return
     */
    @PostMapping("/forget")
    public Result<Void> forgetPassword(@RequestBody ForgetPwdDto forgetPwdDto) {
        System.out.println("1111111111111111111111111111111");

        System.out.println(forgetPwdDto);


        System.out.println("11111111111111111111111");
        if (!Optional.ofNullable(forgetPwdDto).isPresent()) {
            return Result.failure(ResultCode.PARAM_IS_NULL);
        }

        commonService.forgetPassword(forgetPwdDto);

        return Result.success();
    }


    /**
     * 用于判断今日是否为月初
     * @param calendar
     * @return
     */
    public static boolean isFirstDayOfMonth(Calendar calendar) {
        return calendar.get(Calendar.DAY_OF_MONTH) == 1;
    }
    /**
     * 用户登录
     * @param userLoginDto
     * @return
     */
    @PostMapping("/login")
    public Result<UserVo> login(@RequestBody UserLoginDto userLoginDto) {
        if(userLoginDto.getEmail() !=null){
            userLoginDto.setAccount(commonService.GetAccount(userLoginDto.getEmail()));
        }
        System.out.println(userLoginDto);

        Calendar calendar = Calendar.getInstance();
        boolean isFirstDay = isFirstDayOfMonth(calendar);
        System.out.println("今天是 " + calendar.getTime() + ", 是否是月初: " + isFirstDay);
        if (!Optional.ofNullable(userLoginDto).isPresent() ||
                !Optional.ofNullable(userLoginDto.getAccount()).isPresent() ||
                !Optional.ofNullable(userLoginDto.getPassword()).isPresent()) {
            return Result.failure(ResultCode.PARAM_IS_NULL);
        }
        if(commonService.login(userLoginDto) != null&&isFirstDayOfMonth(Calendar.getInstance())){
            Integer totalScore = consumerMapper.GetTotalScore(userLoginDto.getAccount());
            System.out.println(totalScore);
            consumerMapper.SetConsumerScore(userLoginDto.getAccount(),totalScore);
            consumerMapper.DeleteCheckRecordBeforeToday(userLoginDto.getAccount());
        }
        return Result.success(commonService.login(userLoginDto));
    }


    /**
     * 用户退出系统
     *
     * @return
     */
    @GetMapping("/logout")
    public Result<Void> logout() {
        commonService.logout();
        return Result.success();
    }


    /**
     * 用于实现用户注册的功能
     * @param registerDto
     * @return
     */
    @PostMapping("/register")
    public Result<Long> Register(@RequestBody RegisterDto registerDto) {

        if (!Optional.ofNullable(registerDto).isPresent()) {
            return Result.failure(ResultCode.PARAM_IS_NULL);
        }

        if(commonMapper.GetIsExistEmail(registerDto.getEmail()).size()==0){
            Long consumerId = commonService.RegisterView(registerDto);
            return Result.success(consumerId);
        }
        else {
            return Result.success(1L);
        }
    }




    /**
     * 修改头像
     * @param data
     * @return
     */

    @PostMapping("/upload/avatar")
    public Result<String> uploadPicture(@RequestParam("avatar") MultipartFile data,@RequestParam("userId") Long userId) {
//        System.out.println(data);
        String picturePath = CommonUtil.uploadFile(data);
        System.out.println(picturePath);
        String picturePathNew = commonService.uploadPicture(picturePath,userId);
        return Result.success("http://localhost:80/"+picturePathNew);
    }

    @PostMapping("/upload/audio")
    public Result<String> uploadAudio(@RequestParam("file") MultipartFile data) {
        System.out.println(data.isEmpty());
        // 检查文件是否为空
        if (data.isEmpty()) {
            return Result.success("上传文件为空");
        }
//        System.out.println(data);
        String picturePath = CommonUtil.uploadFile(data);
        System.out.println(picturePath);
//        return Result.success("http://localhost:80/"+picturePathNew);
        return Result.success("http://localhost:80/images/"+picturePath);
    }

    /**
     * 用于实现用户注册的功能
     * @param userVo
     * @return
     */
    @PostMapping("/update_information")
    public Result<Void> UpdateUserInfomation(@RequestBody UserVo userVo) {
        commonService.UpdateUserInfomation(userVo);
        return Result.success();
    }





    /**
     * 用于用户在修改邮箱时的后端接口
     * @param modifyEmailDto
     * @return
     */
    @PostMapping("/update_email_information")
    public Result<Void> updateEmailInformation(@RequestBody ModifyEmailDto modifyEmailDto) {
        System.out.println(modifyEmailDto);
        if (!Optional.ofNullable(modifyEmailDto).isPresent()) {
            return Result.failure(ResultCode.PARAM_IS_NULL);
        }

        if(commonMapper.GetIsExistEmail(modifyEmailDto.getNewEmail()).size()==0){
            commonService.UpdateUserEmailInfomation(modifyEmailDto);
            return Result.success();
        }
        return Result.failure(ResultCode.EMAIL_IS_EXIST);
    }

    /**
     *
     * @param userVo
     * @return
     */
    @PostMapping("/update_admin_information")
    public Result<Void> UpdateAdminInfomation(@RequestBody UserVo userVo) {
        commonService.UpdateAdminInfomation(userVo);
        return Result.success();
    }


    /**
     * 用于实现获取文章内容的接口
     * @return
     */
    @GetMapping("/article/get")
    Result<List<ArticleDao>> GetArticle(){
        List<ArticleDao> articleDaos = commonService.GetArticle();
        return Result.success(articleDaos);
    }


    @PostMapping("/update_city")
    Result<Void> UpdateCity(@RequestBody Map<String,String> request){
        Long userId = Long.parseLong(request.get("userId"));
        String city = request.get("city");
        commonService.UpdateCity(userId,city);
        return Result.success();
    }



    @PostMapping("/yuding")
    DataList GetData(@RequestBody Map<String ,String> request){

        System.out.println(request);
        System.out.println(request.get("startDate"));
        DataList dataList = commonService.GetData(request.get("startDate"),request.get("endDate"));
        System.out.println(1);
        return dataList;
    }

    @PostMapping("/jingdian")
    Result<List<Jingdian>> GetJingData(){
        List<Jingdian> jingdians = commonService.GetJingdianData();

        return Result.success(jingdians);
    }


}
